<?php

class ControllerAdmin_Templates extends ControllerAdmin_Base
{
	public function __construct($section) {		
		$this->section      = $section;
		$this->common_vars  = Registry::get("common_vars");
		$this->table_module = PRFX."templates";
	}
	
	public function getFirstPage()
	{
		/* Изменение порядка и проверка на удаление */
		if($_POST['subaction'] == 'updateitems') {			
			$this->confirm = functions::updateItems($_POST, $this->table_module, "por");
		}
		/* Удаление записей */
		elseif($_POST['id_delete']) {
			$this->confirm = functions::deleteItems($_POST, $this->table_module);
		}
		
		/* Список темплейтов */
		$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_module."` ORDER BY `Por`;");
		if (PEAR::isError($r)) {
			die($r->getMessage().' ::: '.$r->getUserInfo());
		}
		if($r->numRows()) {
			while($p = $r->fetchRow(MDB2_FETCHMODE_ASSOC)) {
				$tpl_list[] = $p;
			}
		}		
		Registry::get("smarty")->assign(array(
			'CFG_FIELD'  => array(						
				'edit'   => true,
				'por'    => true,
				'delete' => true,			 
				'field_cfg' => array(
					array(
						'name'      => 'Название раздела',
						'fieldname' => 'name',
						'width'     => '50%',
						'link'      => true,			
						'attr'      => false
					),
					array(
						'name'      => 'Темплейт',
						'fieldname' => 'tpl',
						'width'     => '50%',
						'link'      => true,			
						'attr'      => false
					)
				),
				"aoData" => array(
					"bSortable" => array(
						"false",						
						"false",
						"false",
						"null",
						"null"
					)
				)
			),
			'TBODY_TD'        => $tpl_list,
			'ACT_NAME'        => "templates",
			'CONFIRM'         => $this->confirm
		));		
		return Registry::get("smarty")->fetch(TEMPLATE_ADMIN.$this->common_vars["controller_template"], Registry::get("cache_id"));
	}
	/* Запись в файл */
	private function updateTplCode($tpl, $path, $code) {
		$pathTpl = $path.$tpl;
		if(file_exists($pathTpl) && is_file($pathTpl)) {
			$w = fopen($pathTpl, 'w');
			fwrite($w, $code);
			fclose($w);
		}
	}
	
	public function init(){}	
	public function addToTable()
	{
		if(!empty($_POST['type'])) {				
			extract($_POST);
			
			$date_update = date("Y-m-d H:i:s");					
			if ($_POST['type'] == 'add') {
				$date_create = date("Y-m-d H:i:s");	
				eval(functions::insert_sql($this->table_module, 'sql'));
				$r =& Registry::get("MDB")->query($sql);		
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}
			}
			elseif($_POST['type'] == 'editt')
			{					
				self::updateTplCode($tpl, TEMPLATE_SITE, $last_backup_site);
				self::updateTplCode($tpl, TEMPLATE_ADMIN, $last_backup_admin);				
				
				eval(functions::update_sql($this->table_module, 'sql', 'id', $_POST['id']));				
				$r =& Registry::get("MDB")->query($sql);		
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}
			}
		}
	}
	
    public function out()
	{
		self::addToTable();
		
		if(empty($_GET['type'])) {
			$this->action = '<div class="addbuttons"><a href="?m=templates&type=add" class="ui_wo_buttons ui-state-default ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Добавить темплейт</a></div>';			
			return self::getFirstPage();
		}		
		else
		{
			if($_GET['type'] == 'edit')
			{							   
				$r =& Registry::get("MDB")->query("SELECT * FROM `".$this->table_module."` WHERE `ID`='".$_GET['id']."' LIMIT 1;");
				if (PEAR::isError($r)) {
					die($r->getMessage().' ::: '.$r->getUserInfo());
				}
				if($r->numRows()) {
					$Field = $r->fetchRow(MDB2_FETCHMODE_ASSOC);
				}
			}			
			elseif($_GET['type'] == 'add' || empty($_GET['type'])) {
				$Field["por"] = functions::incrPor($this->table_module);			
			}
			
			/* Темплейт сайта */
			$filenameTpl = TEMPLATE_SITE.$Field["tpl"];
			if(file_exists($filenameTpl) && is_file($filenameTpl)) {
				$FOpen = fopen($filenameTpl, 'r');
				$Field["last_backup_site"] = htmlspecialchars(@fread($FOpen, filesize($filenameTpl)));
				fclose($FOpen);
			}
			else {
				$Field["tpl_none_site"] = 1;
			}			
			/* Темплейт админ */
			$filenameTpl = TEMPLATE_ADMIN.$Field["tpl"];
			if(file_exists($filenameTpl) && is_file($filenameTpl)) {
				$FOpen = fopen($filenameTpl, 'r');
				$Field["last_backup_admin"] = htmlspecialchars(@fread($FOpen, filesize($filenameTpl)));
				fclose($FOpen);
			}
			else {
				$Field["tpl_none_admin"] = 1;
			}
			Registry::get("smarty")->assign(array(			
				'Field' => $Field
			));
			return Registry::get("smarty")->fetch(TEMPLATE_ADMIN.$this->common_vars["controller_template"], Registry::get("cache_id"));
		}		
    }
}

$controller = new ControllerAdmin_Templates($section);
$ob_admin_out = $controller->out();
$ob_admin_action = $controller->action;

?>